package com.example.application;

import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

// Coil 相关的 import
import coil.Coil;
import coil.request.ImageRequest;
import coil.transform.BlurTransformation;

// ... 其他 import 保持不变 ...
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.widget.IjkVideoView;

public class MainActivity extends AppCompatActivity implements IjkVideoView.OnStateChangeListener {

    // ... 所有其他字段和方法保持不变 ...
    private IjkVideoView videoView;
    private IjkMediaPlayer ijkMediaPlayer;
    private EditText etUrl;
    private ImageButton btnPlayUrl, btnPlayPause, btnInfo, btnCloseInfo;
    private SeekBar seekBar;
    private TextView tvCurrentTime, tvTotalTime, tvVideoInfo;
    private LinearLayout videoInfoContainer, blurContainer;
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable updateProgressAction;
    private boolean isTrackingSeekBar = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        disableSSLCertificateChecking();
        initViews();
        setupBlurBackground(); // 调用新的模糊背景方法
        setupPlayer();
        setupClickListeners();
        setupProgressBar();
    }

    private void initViews() {
        videoView = findViewById(R.id.video_view);
        etUrl = findViewById(R.id.et_url);
        btnPlayUrl = findViewById(R.id.btn_play_url);
        btnPlayPause = findViewById(R.id.btn_play_pause);
        btnInfo = findViewById(R.id.btn_info);
        btnCloseInfo = findViewById(R.id.btn_close_info);
        seekBar = findViewById(R.id.seek_bar);
        tvCurrentTime = findViewById(R.id.tv_current_time);
        tvTotalTime = findViewById(R.id.tv_total_time);
        tvVideoInfo = findViewById(R.id.tv_video_info);
        videoInfoContainer = findViewById(R.id.video_info_container);
        blurContainer = findViewById(R.id.blur_container);
    }

    /**
     * 使用 Coil 库来设置模糊背景
     */
    private void setupBlurBackground() {
        // 创建一个 ImageRequest 来加载图片
        ImageRequest request = new ImageRequest.Builder(this)
			// 使用一个占位图，例如应用图标
			.data(R.drawable.ic_launcher_background)
			// 设置目标为 blur_container
			.target(blurContainer)
			// 应用模糊变换，半径为 25f
			.transformations(new BlurTransformation(this, 25f))
			.build();

        // 使用 Coil 的 ImageLoader 来执行请求
        Coil.imageLoader(this).enqueue(request);
    }

    // ... setupPlayer, setupClickListeners, updateProgress 等所有其他方法保持不变 ...
    private void setupPlayer() {
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        ijkMediaPlayer = new IjkMediaPlayer();
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "protocol_whitelist", "crypto,http,https,tcp,tls,udp,rtmp,rtsp,rtp,file,concat,ffrtmphttp");
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "tls_verify_host", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "tls_verify_peer", 0);
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36");
        ijkMediaPlayer.setDataSourceHeaders(headers);
        videoView.setMediaPlayer(ijkMediaPlayer);
        videoView.setOnStateChangeListener(this);
    }

    private void setupClickListeners() {
        btnPlayUrl.setOnClickListener(v -> {
            String url = etUrl.getText().toString().trim();
            if (!url.isEmpty()) {
                videoView.setVideoURI(Uri.parse(url));
                videoView.start();
            } else {
                Toast.makeText(this, "Please enter a video URL", Toast.LENGTH_SHORT).show();
            }
        });
        btnPlayPause.setOnClickListener(v -> {
            if (videoView.isPlaying()) {
                videoView.pause();
            } else {
                videoView.start();
            }
        });
        btnInfo.setOnClickListener(v -> {
            if (videoInfoContainer.getVisibility() == View.GONE) {
                videoInfoContainer.setVisibility(View.VISIBLE);
                updateVideoInfo();
            } else {
                videoInfoContainer.setVisibility(View.GONE);
            }
        });
        btnCloseInfo.setOnClickListener(v -> videoInfoContainer.setVisibility(View.GONE));
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
				@Override
				public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
					if (fromUser) {
						long duration = videoView.getDuration();
						if (duration > 0) {
							long position = (long) (progress * duration / 100.0);
							videoView.seekTo(position);
						}
					}
				}
				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					isTrackingSeekBar = true;
				}
				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					isTrackingSeekBar = false;
				}
			});
    }

    private void setupProgressBar() {
        updateProgressAction = this::updateProgress;
    }

    private void updateProgress() {
        if (!isTrackingSeekBar && videoView.isPlaying()) {
            long position = videoView.getCurrentPosition();
            long duration = videoView.getDuration();
            tvCurrentTime.setText(formatTime(position));
            if (duration > 0) {
                tvTotalTime.setText(formatTime(duration));
                seekBar.setProgress((int) (position * 100 / duration));
            }
        }
        handler.postDelayed(updateProgressAction, 1000);
    }

    @Override
    public void onStateChange(int newState) {
        switch (newState) {
            case IjkVideoView.STATE_PREPARED:
                tvTotalTime.setText(formatTime(videoView.getDuration()));
                updateProgress();
                break;
            case IjkVideoView.STATE_PLAYING:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_pause);
                break;
            case IjkVideoView.STATE_PAUSED:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
                break;
            case IjkVideoView.STATE_PLAYBACK_COMPLETED:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
                break;
            case IjkVideoView.STATE_ERROR:
                Toast.makeText(this, "Playback Error", Toast.LENGTH_SHORT).show();
                btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
                break;
        }
    }

    private void updateVideoInfo() {
        StringBuilder info = new StringBuilder();
        if (ijkMediaPlayer != null) {
            info.append("Player Information:\n");
            info.append("Video Duration: ").append(formatTime(videoView.getDuration())).append("\n");
            info.append("Current Position: ").append(formatTime(videoView.getCurrentPosition())).append("\n");
            info.append("Video Resolution: ").append(ijkMediaPlayer.getVideoWidth()).append("x").append(ijkMediaPlayer.getVideoHeight()).append("\n");
            info.append("Video Codec: ").append(ijkMediaPlayer.getVideoCodecInfo()).append("\n");
            info.append("Audio Codec: ").append(ijkMediaPlayer.getAudioCodecInfo()).append("\n");
            info.append("Sample Rate: ").append(ijkMediaPlayer.getAudioSampleRate()).append(" Hz\n");
            info.append("Channels: ").append(ijkMediaPlayer.getAudioChannels()).append("\n");
            info.append("Bitrate: ").append(ijkMediaPlayer.getBitrate()).append(" bps\n");
            info.append("Player State: ").append(getStateString(videoView.getCurrentState())).append("\n");
        }
        tvVideoInfo.setText(info.toString());
    }

    private String getStateString(int state) {
        switch (state) {
            case IjkVideoView.STATE_IDLE: return "Idle";
            case IjkVideoView.STATE_PREPARING: return "Preparing";
            case IjkVideoView.STATE_PREPARED: return "Prepared";
            case IjkVideoView.STATE_PLAYING: return "Playing";
            case IjkVideoView.STATE_PAUSED: return "Paused";
            case IjkVideoView.STATE_PLAYBACK_COMPLETED: return "Completed";
            case IjkVideoView.STATE_ERROR: return "Error";
            default: return "Unknown";
        }
    }

    private String formatTime(long timeMs) {
        if (timeMs <= 0) return "00:00";
        long totalSeconds = timeMs / 1000;
        long hours = totalSeconds / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        if (hours > 0) {
            return String.format("%02d:%02d:%02d", hours, minutes, seconds);
        } else {
            return String.format("%02d:%02d", minutes, seconds);
        }
    }

    private void disableSSLCertificateChecking() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
				new X509TrustManager() {
					public X509Certificate[] getAcceptedIssuers() {
						return null;
					}
					public void checkClientTrusted(X509Certificate[] certs, String authType) {}
					public void checkServerTrusted(X509Certificate[] certs, String authType) {}
				}
            };
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null && videoView.canPause()) {
            videoView.pause();
        }
        handler.removeCallbacks(updateProgressAction);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(updateProgressAction);
        if (videoView != null) {
            videoView.stopPlayback();
            videoView.release(true);
            videoView = null;
        }
        if (ijkMediaPlayer != null) {
            ijkMediaPlayer.release();
            ijkMediaPlayer = null;
        }
        IjkMediaPlayer.native_profileEnd();
    }
}

